package com.slz3.business.generator;

import com.slz3.business.BusinessRouter;
import com.slz3.business.frame.util.HumpToUnderline;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;
import java.nio.charset.Charset;
import java.nio.file.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @auhtor buerjun
 * @date 2018-11-02
 * @desc 生成angular项目module
 */
public class CloneAngularModuleTemplateGenerator {

    private static final String STATIC_FIELD = "INS_IM_MANAGE";
    //angular项目根目录,根据自己项目的路径修改
    private final String ROOT = "/Users/lemo-wu/Documents/gitlab/mishang-business-angular/";
    private final String PROJECT_MODULE = "src/app/module/";
    private final String moudle = ROOT + PROJECT_MODULE;

    private static String TARGET_CHILD_DIC;
    static {
        try {
            Field field = BusinessRouter.class.getDeclaredField(STATIC_FIELD);
            BusinessRouter router = BusinessRouter.class.newInstance();
            field.setAccessible(true);
            TARGET_CHILD_DIC = field.get(router).toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    String[] split = TARGET_CHILD_DIC.split("/");
    String first = split[1];
    String second = split[2];
    String firstCharUpper = String.valueOf(first.charAt(0)).toUpperCase() + first.substring(1);
    String secondCharUpper = String.valueOf(second.charAt(0)).toUpperCase() + second.substring(1);

    public static void main(String[] args) throws Exception {
        CloneAngularModuleTemplateGenerator generator = new CloneAngularModuleTemplateGenerator();
        //生成功能模块路由
        generator.generatorRoute();
        //生成功能模块
        generator.generatorMoudle();
        //生成功能模块组件
        generator.generatorComponent();
        //生成功能模块测试
        generator.generatorSpec();
        //将生成的路由添加到根路由中
        generator.updateGlobalRouteModule();

    }

    ///Users/lemo-wu/Documents/gitlab/mishang-business-angular/src/app/module/module-routing.module.ts
    private void updateGlobalRouteModule() {
        String SOURCE  = moudle + "module-routing.module.ts";
        Path SOURCE_PATH = Paths.get(SOURCE);

        String replace = HumpToUnderline.convert(first).replace("_", "-");

        String insert = "            {path: '"+replace+"', loadChildren: './"+replace+"/"+replace+".module#"+firstCharUpper+"Module'},";


        try {
            List<String> lines = Files.readAllLines(SOURCE_PATH);
            List<String> targetLines = new ArrayList<>(lines.size());
            for (int i = 0; i < lines.size(); i++) {
                String line = lines.get(i);
                targetLines.add(line);
                if (line.contains("this line is for module route don't remove")) {
                    targetLines.add(insert);
                }
            }
            //todo 需要还原SOURCE_PATH
            Files.write(SOURCE_PATH, targetLines);

        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    ///Users/lemo-wu/Documents/gitlab/mishang-business-angular/src/app/module/goods-management/goods-management.component.spec.ts
    private void generatorSpec() {

        String replace = HumpToUnderline.convert(first).replace("_", "-");

        String spec = "import { async, ComponentFixture, TestBed } from '@angular/core/testing';\n" +
                "import { "+firstCharUpper+"Component } from './"+replace+".component';\n" +
                "describe('"+firstCharUpper+"Component', () => {\n" +
                "  let component: "+firstCharUpper+"Component;\n" +
                "  let fixture: ComponentFixture<"+firstCharUpper+"Component>;\n" +
                "  beforeEach(async(() => {\n" +
                "    TestBed.configureTestingModule({\n" +
                "      declarations: [ "+firstCharUpper+"Component ]\n" +
                "    })\n" +
                "    .compileComponents();\n" +
                "  }));\n" +
                "  beforeEach(() => {\n" +
                "    fixture = TestBed.createComponent("+firstCharUpper+"Component);\n" +
                "    component = fixture.componentInstance;\n" +
                "    fixture.detectChanges();\n" +
                "  });\n" +
                "  it('should create', () => {\n" +
                "    expect(component).toBeTruthy();\n" +
                "  });\n" +
                "});\n";

        Path TARGET = Paths.get(
                moudle + replace + "/" + replace + ".component.spec.ts");
        if (Files.exists(TARGET)) {
            return;
        }
        Path targetParent = TARGET.getParent();
        try {
            if (Files.notExists(targetParent)) {
                Files.createDirectories(targetParent);
            }
            if (Files.notExists(TARGET)){
                Files.createFile(TARGET);
            }
            Files.write(TARGET,spec.getBytes(Charset.defaultCharset()) );
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println(spec);
    }

    //Users/lemo-wu/Documents/gitlab/mishang-business-angular/src/app/module/goods-management/goods-management.component.ts
    private void generatorComponent() {

        String replace = HumpToUnderline.convert(first).replace("_", "-");

        String component = "import { Component, OnInit } from '@angular/core';\n" +
                "@Component({\n" +
                "  selector: 'app-"+replace+"',\n" +
                "  template: '<router-outlet></router-outlet>'\n" +
                "})\n" +
                "export class "+firstCharUpper+"Component implements OnInit {\n" +
                "  constructor() { }\n" +
                "  ngOnInit() {\n" +
                "  }\n" +
                "}\n";

        Path TARGET = Paths.get(
                moudle + replace + "/" + replace + ".component.ts");
        if (Files.exists(TARGET)) {
            return;
        }
        Path targetParent = TARGET.getParent();
        try {
            if (Files.notExists(targetParent)) {
                Files.createDirectories(targetParent);
            }
            if (Files.notExists(TARGET)){
                Files.createFile(TARGET);
            }
            Files.write(TARGET,component.getBytes(Charset.defaultCharset()) );
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println(component);
    }

    ///Users/lemo-wu/Documents/gitlab/mishang-business-angular/src/app/module/goods-management/goods-management.module.ts
    private void generatorMoudle() {
        String replace = HumpToUnderline.convert(first).replace("_", "-");

        String moudle = "import {NgModule} from '@angular/core';\n" +
                "import {CommonModule} from '@angular/common';\n" +
                "import {"+firstCharUpper+"RoutingModule} from './"+replace+"-routing.module';\n" +
                "import {"+firstCharUpper+"Component} from './"+replace+".component';\n" +
                "@NgModule({\n" +
                "    declarations: [\n" +
                "        "+firstCharUpper+"Component\n" +
                "    ],\n" +
                "    imports: [\n" +
                "        CommonModule,\n" +
                "        "+firstCharUpper+"RoutingModule\n" +
                "    ],\n" +
                "    providers: []\n" +
                "})\n" +
                "export class "+firstCharUpper+"Module {\n" +
                "}\n";
        Path TARGET = Paths.get(
                this.moudle + replace + "/" + replace + ".module.ts");
        if (Files.exists(TARGET)) {
            return;
        }
        Path targetParent = TARGET.getParent();
        try {
            if (Files.notExists(targetParent)) {
                Files.createDirectories(targetParent);
            }
            if (Files.notExists(TARGET)){
                Files.createFile(TARGET);
            }
            Files.write(TARGET,moudle.getBytes(Charset.defaultCharset()) );
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println(moudle);
    }

    private void generatorRoute() {
        String replace = HumpToUnderline.convert(first).replace("_", "-");
        String secondReplace = HumpToUnderline.convert(second).replace("_", "-");
        String route = "import {RouterModule, Routes} from '@angular/router';\n" +
                "import {NgModule} from '@angular/core';\n" +
                "import {" + firstCharUpper + "Component} from './" + replace + ".component';\n" +
                "const routes: Routes = [\n" +
                "    {path: '', component: " + firstCharUpper + "Component,\n" +
                "        children: [\n" +
                "            {path: '', redirectTo: '" + secondReplace + "', pathMatch: 'full'},\n" +
                "            // this line is use for generator path, don't remove\n" +
                "        ]\n" +
                "    }\n" +
                "];\n" +
                "@NgModule({\n" +
                "    imports: [RouterModule.forChild(routes)],\n" +
                "    exports: [RouterModule]\n" +
                "})\n" +
                "export class " + firstCharUpper + "RoutingModule {\n" +
                "}\n";

        ///Users/lemo-wu/Documents/gitlab/mishang-business-angular/src/app/module/goods-management/goods-management-routing.module.ts
        Path TARGET = Paths.get(
                moudle + replace + "/" + replace + "-routing.module.ts");
        if (Files.exists(TARGET)) {
            return;
        }
        Path targetParent = TARGET.getParent();
        try {
            if (Files.notExists(targetParent)) {
                Files.createDirectories(targetParent);
            }
            if (Files.notExists(TARGET)){
                Files.createFile(TARGET);
            }
            Files.write(TARGET,route.getBytes(Charset.defaultCharset()) );
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println(route);
    }


}
